/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.profile;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.ResponseHandlerInterface;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.BaseOnScrollListener;
import com.tstudy.laoshibang.base.BaseOnScrollListener.FirstPositionCallBack;
import com.tstudy.laoshibang.base.BaseOnScrollListener.LoadMoreCallBack;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.CONSTANT.LoadType;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.camera.CommunityPublishActivity;
import com.tstudy.laoshibang.community.CommunityDetailActivity;
import com.tstudy.laoshibang.community.CommunityMessageListFragment;
import com.tstudy.laoshibang.custom.RoundImageView;
import com.tstudy.laoshibang.mode.MyCommunity;
import com.tstudy.laoshibang.mode.User;
import com.tstudy.laoshibang.mode.request.Conds;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.mode.response.MyCommunityListResponse;
import com.tstudy.laoshibang.profile.MyCommunityAdapter.AdapterCallBack;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import de.greenrobot.event.EventBus;
@SuppressLint("InflateParams")
@EFragment(R.layout.my_community)
public class MyCommunityFragment extends BaseFragment{
	final static String TAG = "my_community";
	public MyCommunityFragment() {
		super();
	}
	
	@ViewById(R.id.my_community_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.my_community_progress)
	RelativeLayout mProgressLayout;
	
	@ViewById(R.id.my_community_list)
	PullToRefreshListView mPullToRefreshListView;
	
	@ViewById(R.id.my_community_title)
	TextView mTitleTxt;
	@ViewById(R.id.my_community_message)
	ImageView mTitleMessage;
	
	@ViewById(R.id.my_community_header_sign)
	EditText mSignExt;
	
	BaseOnScrollListener mBaseOnScrollListener;
	LoadType mLoadType;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	MyCommunityAdapter mCommunityListAdapter;
	int mCurrentPosition = 0;
	List<View> mViewList = new ArrayList<View>();
	List<MyCommunity> mMyCommunitys = new ArrayList<MyCommunity>();
	int mNewCount;
	@StringRes(R.string.select_all)
	String mSelectAllStr;
	int mSelectAllKey = -1;
	String mToUserNo;
	User mToUser;
	String mGroupId;

	public static void add(int containerViewId,String toUserNo, String mGroupId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		args.putString(CONSTANT.ARGS.USER_NO, toUserNo);
		args.putString(CONSTANT.ARGS.GROUP_ID, mGroupId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,MyCommunityFragment_.class.getName(),args);
		((BaseActivity)BaseApplication.mCurrentActivity).add(containerViewId,fragment,TAG);	
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		EventBus.getDefault().register(this);
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mRootLayout.setOnClickListener(null);
			initHeaderView();
			mCommunityListAdapter = new MyCommunityAdapter();
			mPullToRefreshListView.setAdapter(mCommunityListAdapter);
			mCommunityListAdapter.setAdatperCallBack(new AdapterCallBack() {
				@Override
				public void onViewClick(int type,int communityId,String groupId) {
					boolean is_offical = type == 1 ? true : false;
					CommunityDetailActivity.show(is_offical, communityId, BaseApplication.mUserNo,false,-1,groupId);
				}
				@Override
				public void onDeleteClick(int communityId, int position) {
					deleteCommunity(communityId, position);
				}
				@Override
				public void onPublishCommunity() {
					CommunityPublishActivity.show();
				}
			});
			mLoadType = LoadType.load_first;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					getMyCommunityList(true);
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
			mBaseOnScrollListener = new BaseOnScrollListener(new LoadMoreCallBack() {
				@Override
				public void loadMore() {
					mPullToRefreshListView.startLoadMore();
					mLoadType = LoadType.load_more;
					getMyCommunityList(false);
				}
			});
			mBaseOnScrollListener.setFirstPositionCallBack(new FirstPositionCallBack() {
				@Override
				public void firstPosition(int firstPosition) {
					mCurrentPosition = firstPosition;
				}
			});
			mPullToRefreshListView.getRefreshableView().addHeaderView(mHeaderLayout);
			mPullToRefreshListView.setOnScrollListener(mBaseOnScrollListener);
			mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					mLoadType = LoadType.load_refresh;
					getMyCommunityList(true);
				}
			});
		}
	}
	
	public void updateUserInfo(String key,String value,int type){
		ResponseHandlerInterface response = new BaseJsonHandler<BaseResponse>() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (response != null && response.getErr() == CONSTANT.NO_ERROR_STATUS) {
					BaseApplication.showToast(R.string.common_save_success);
					showSoftKeyBoard(mSignExt,false);
				} else {
                    BaseApplication.showToast(R.string.common_save_failed);
                }
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().updateUserInfo(BaseApplication.mUserNo, key, value,type,response);
	}
	
	@Click({R.id.my_community_back,R.id.my_community_message,R.id.my_community_header_avatar})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.my_community_back:
			backAction(mFragmentId);
			showSoftKeyBoard(mSignExt, false);
			break;
		case R.id.my_community_message:
			CommunityMessageListFragment.add(BaseApplication.mUserNo,false,mFragmentId);
			break;
		default:
			break;
		}
	}
	
	RelativeLayout mHeaderLayout;
	RoundImageView mAvatar;
	ImageView mTheme;
	TextView mName;
	
	public void initHeaderView(){
		mHeaderLayout = (RelativeLayout) mInflater.inflate(R.layout.my_community_header, null);
		mAvatar = (RoundImageView) mHeaderLayout.findViewById(R.id.my_community_header_avatar);
		mTheme = (ImageView) mHeaderLayout.findViewById(R.id.my_community_header_theme);
		mName = (TextView) mHeaderLayout.findViewById(R.id.my_community_header_name);
		mSignExt = (EditText) mHeaderLayout.findViewById(R.id.my_community_header_sign);
		
	}
	public void setHeaderView(){
		mTitleTxt.setVisibility(View.VISIBLE);
		mCommunityListAdapter.isSameUser = mToUser.isSameUser;
		mSignExt.setText(mToUser.sign);
		if (mToUser.isSameUser==1) {//我的个人主页
			mTitleMessage.setVisibility(View.VISIBLE);
			mSignExt.setEnabled(true);
			mSignExt.setOnEditorActionListener(new OnEditorActionListener() {
				@Override
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//					if(actionId == EditorInfo.IME_ACTION_GO){
					LogUtil.d("---------execute login actionId==" + actionId + ",--event==" + event);
					if (event == null) {//onEditorAction方法执行两次
						updateUserInfo("sign", mSignExt.getText().toString(), CONSTANT.UPDATE_TYPE_STRING);
					}
//					}
					return false;
				}
			});
		}else{
			mTitleTxt.setText(mToUser.nick + "的吐槽");
			mTitleMessage.setVisibility(View.GONE);
			mSignExt.setHint("");
			mSignExt.setEnabled(false);
		}
		mName.setText(mToUser.nick);
		mAvatar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				BigHeaderActivity.show(mToUser.imgIdxName);
			}
		});
		HttpManager.getInstance().loadEditAvatar(mAvatar, mToUser.imgIdxName,R.drawable.myhome_headerimgbg);
	}
	private void deleteCommunity(int communityId,final int position){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					mMyCommunitys.remove(position);
					mCommunityListAdapter.setData(mMyCommunitys);
					int selection = Math.min(position, mMyCommunitys.size());
					mPullToRefreshListView.getRefreshableView().setSelection(selection);
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().deleteCommunity(BaseApplication.mUserNo, communityId, mGroupId, response);
	}

	private void getMyCommunityList(boolean isUser){
		if (mIsLoading) {
			return ;
		}
		if (mLoadType == LoadType.load_more) {
			start += pageSize;
//			limit += pageSize;
		}else{
			start = 0;
			limit = pageSize;
		}
		mIsLoading = true;
		BaseListJsonHandler<MyCommunityListResponse> response = new BaseListJsonHandler<MyCommunityListResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, MyCommunityListResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.getData() != null) {
						mToUser = response.getData().user;
						if (mToUser != null) {
								setHeaderView();
						}
						if (mLoadType == LoadType.load_more) {
							if (mMyCommunitys.size() == response.getData().getCount()) {
								mBaseOnScrollListener.mIsEnd = true;
							}
						}else{
							mMyCommunitys.clear();
						}
						List<MyCommunity> list = response.getData().getList();
						if (list != null && list.size() > 0) {
							if (mToUser != null && mToUser.isSameUser == 1) {
								if (!CommonUtil.isToday(list.get(0).createTime)) {
									mMyCommunitys.add(new MyCommunity());
									mNewCount =1;
								}else{
									mNewCount = 0;
								}
								
							}else{
								mNewCount = 0;
							}
							mMyCommunitys.addAll(list);
						}else{//进入我的吐槽没有记录显示添加icon
							if (mToUser != null && mToUser.isSameUser == 1) {
								mMyCommunitys.add(new MyCommunity());
								mNewCount = 1;
							}
						}
						if (mLoadType == LoadType.load_more) {
							if (mMyCommunitys.size() - mNewCount == response.getData().getCount()) {
								mBaseOnScrollListener.mIsEnd = true;
							}
						}else{
							mBaseOnScrollListener.mIsEnd = false;
						}
						mCommunityListAdapter.setData(mMyCommunitys);
					}
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					MyCommunityListResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected MyCommunityListResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,MyCommunityListResponse.class);
			}
		};
		List<Conds> conds = new ArrayList<Conds>();
		HttpManager.getInstance().getMyCommunityList(BaseApplication.mUserNo,mToUserNo,mGroupId,start,limit, null,conds,isUser,response);
		
	}
	
	public void onEventMainThread(Object object) {//发布成功后更新列表
		mLoadType = LoadType.load_first;
		getMyCommunityList(true);
	}

	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
		if(mLoadType == LoadType.load_more){
			if (mBaseOnScrollListener.mIsEnd) {
				mPullToRefreshListView.endLoadMore(BaseApplication.getResString(R.string.community_no_more_data));
			}else{
				mPullToRefreshListView.stopLoadMore();
			}
		}
		if(mPullToRefreshListView != null){
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mPullToRefreshListView != null){
						mPullToRefreshListView.onRefreshComplete();
						LogUtil.d("--onRefreshComplete afterloading");
					}
				}
			}, 1000);
		}
	
	}
	@Override
	public void clear() {
		showSoftKeyBoard(mSignExt, false);
	}
	
	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
			mToUserNo = args.getString(CONSTANT.ARGS.USER_NO);
			mGroupId = args.getString(CONSTANT.ARGS.GROUP_ID);
		}
	}

}
